package org.easy.tencim;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.easy.core.util.HttpUtil;
import org.easy.tencim.model.msgcontent.TIMTextElem;
import org.easy.tencim.model.msgcontent.TimBaseElem;
import org.easy.tencim.util.TLSSigAPIv2;
import org.apache.commons.lang3.RandomUtils;
import org.easy.tencim.model.AccountInfo;
import org.easy.tencim.model.CommonSendMsg;
import org.easy.tencim.model.IMConstant;
import org.easy.tencim.model.IMResponseMsg;
import org.easy.tencim.model.MsgBodyInfo;

import java.util.*;

/**
 * @author: Li chaojie
 * @Date: 2022/3/21
 * @Description: https://cloud.tencent.com/document/product/269/1520
 */
public class TencentImTemplate {

    private final Long appid;
    private final String key;
    private final Integer expire;

    public TencentImTemplate(Long appid, String key, Integer expire) {
        this.appid = appid;
        this.key = key;
        this.expire = expire;
    }

    public static void main(String[] args) {
        TLSSigAPIv2 apIv2 = new TLSSigAPIv2(1600055743, "39dc8f2f448751816883744f5db35612bcfaa7ea13a5dd38cfc1e1c72fad8e37");
        System.out.println(apIv2.genUserSig("administrator", 16000));


    }

    /**
     * 获取签名用户的访问票据
     *
     * @param sid
     * @return
     */
    public String getSign(String sid) {
        TLSSigAPIv2 apIv2 = new TLSSigAPIv2(appid, key);
        return apIv2.genUserSig(sid, expire);
    }

    /**
     * 账号导入
     *
     * @param sid
     * @return
     */
    public IMResponseMsg accountImport(String sid) {
        return accountImport(sid, sid);
    }

    /**
     * 账号导入
     *
     * @param sid
     * @return
     */
    public IMResponseMsg accountImport(String sid, String nick) {
        AccountInfo accountInfo = new AccountInfo();
        accountInfo.setIdentifier(sid);
        accountInfo.setNick(nick);

        String result = HttpUtil.postJsonStr(getHttpsUrl(IMConstant.IM_ACCOUNT_IMPORT, IMConstant.ROLE_ADMINISTRATOR), JSON.toJSONString(accountInfo));
        return JSON.parseObject(result, IMResponseMsg.class);
    }

    public IMResponseMsg accountDelete(String sid) {
        AccountInfo accountInfo = new AccountInfo();
        accountInfo.setIdentifier(sid);

        String result = HttpUtil.postJsonStr(getHttpsUrl(IMConstant.IM_ACCOUNT_DELETE, IMConstant.ROLE_ADMINISTRATOR), JSON.toJSONString(accountInfo));
        return JSON.parseObject(result, IMResponseMsg.class);
    }

    private String getHttpsUrl(String imServiceApi, String identifier) {
        return String.format("%s%s?sdkappid=%s&identifier=%s&usersig=%s&random=%s&contenttype=json",
                IMConstant.TENCENT_BASE_URL,
                imServiceApi,
                appid,
                identifier,
                getSign(identifier),
                new Random().nextInt());
    }

    /**
     * 发送文本消息 通过内置管理员角色
     *
     * @param fromAccount
     * @param toAccount
     * @param data
     * @return
     */
    public IMResponseMsg sendMessage(String fromAccount, String toAccount, Object data) {
        return sendMessage(IMConstant.ROLE_ADMINISTRATOR, fromAccount, toAccount, data);
    }

    /**
     * 发送文本消息
     *
     * @param identifier
     * @param fromAccount
     * @param toAccount
     * @param data
     * @return
     */
    public IMResponseMsg sendMessage(String identifier, String fromAccount, String toAccount, Object data) {
        TIMTextElem elem = new TIMTextElem();
        elem.setText(JSON.toJSONString(data));

        CommonSendMsg commonSendMsg = new CommonSendMsg();
        commonSendMsg.setSyncOtherMachine(2);
        commonSendMsg.setFrom_Account(fromAccount);
        commonSendMsg.setTo_Account(toAccount);
        commonSendMsg.setMsgSeq((int) (System.currentTimeMillis() / 1000));
        commonSendMsg.setMsgRandom(Math.abs(new Random().nextInt()));
        commonSendMsg.setMsgTimeStamp((int) (System.currentTimeMillis() / 1000));

        MsgBodyInfo bodyInfo = new MsgBodyInfo();
        bodyInfo.setMsgContent(elem);

        List<MsgBodyInfo> bodyInfos = new ArrayList<>();
        bodyInfos.add(bodyInfo);
        commonSendMsg.setMsgBody(bodyInfos);

        String result = HttpUtil.postJsonStr(getHttpsUrl(IMConstant.IM_SEND_MSG, identifier), JSON.toJSONString(commonSendMsg));
        return JSON.parseObject(result, IMResponseMsg.class);
    }


    public IMResponseMsg sendMessage(String fromAccount, String toAccount, TimBaseElem data) {
        return sendMessage(IMConstant.ROLE_ADMINISTRATOR, fromAccount, toAccount, data);
    }

    public IMResponseMsg sendMessage(String identifier, String fromAccount, String toAccount, TimBaseElem timBaseElem) {
        CommonSendMsg commonSendMsg = new CommonSendMsg();
        commonSendMsg.setSyncOtherMachine(2);
        commonSendMsg.setFrom_Account(fromAccount);
        commonSendMsg.setTo_Account(toAccount);
        commonSendMsg.setMsgSeq((int) (System.currentTimeMillis() / 1000));
        commonSendMsg.setMsgRandom(Math.abs(new Random().nextInt()));
        commonSendMsg.setMsgTimeStamp((int) (System.currentTimeMillis() / 1000));

        MsgBodyInfo bodyInfo = new MsgBodyInfo();
        bodyInfo.setMsgContent(timBaseElem);

        List<MsgBodyInfo> bodyInfos = new ArrayList<>();
        bodyInfos.add(bodyInfo);
        commonSendMsg.setMsgBody(bodyInfos);

        String result = HttpUtil.postJsonStr(getHttpsUrl(IMConstant.IM_SEND_MSG, identifier), JSON.toJSONString(commonSendMsg, SerializerFeature.QuoteFieldNames));
        return JSON.parseObject(result, IMResponseMsg.class);
    }


    /**
     * 创建公共群组
     * https://cloud.tencent.com/document/product/269/1615
     *
     * @return
     */
    public IMResponseMsg createPublicGroup(String groupId, List<String> memberAccounts) {
        Map<String, Object> createGroup = new HashMap<>();
        createGroup.put("Type", "Public");
        createGroup.put("Name", groupId);
        createGroup.put("GroupId", groupId);

        List<Map<String, Object>> memberList = new ArrayList<>();
        for (String memberAccount : memberAccounts) {
            Map<String, Object> mem = new HashMap<>();
            mem.put("Member_Account", memberAccount);
            memberList.add(mem);
        }
        createGroup.put("MemberList", memberList);

        String result = HttpUtil.postJsonStr(getHttpsUrl(IMConstant.CREATE_GROUP, IMConstant.ROLE_ADMINISTRATOR), JSON.toJSONString(createGroup));
        return JSON.parseObject(result, IMResponseMsg.class);
    }

    /**
     * 发送消息
     * https://cloud.tencent.com/document/product/269/1629
     *
     * @return
     */
    public IMResponseMsg sendGroupMsg(String groupId, String fromAccount, TimBaseElem data) {
        Map<String, Object> sendGroupMsg = new HashMap<>();
        sendGroupMsg.put("GroupId", groupId);
        sendGroupMsg.put("Random", RandomUtils.nextInt(0, 2094967295));
        sendGroupMsg.put("From_Account", fromAccount);
        sendGroupMsg.put("MsgBody", data);

        String result = HttpUtil.postJsonStr(getHttpsUrl(IMConstant.IM_GROUP_SEND_MSG, IMConstant.ROLE_ADMINISTRATOR), JSON.toJSONString(sendGroupMsg));
        return JSON.parseObject(result, IMResponseMsg.class);
    }


    public IMResponseMsg deleteC2cMsgRamble(String peerAccount, List<String> msgKeyList) {
        Map<String, Object> sendGroupMsg = new HashMap<>();
        sendGroupMsg.put("Operator_Account", IMConstant.ROLE_ADMINISTRATOR);
        sendGroupMsg.put("Peer_Account", peerAccount);
        sendGroupMsg.put("MsgKeyList", msgKeyList);


        String result = HttpUtil.postJsonStr(getHttpsUrl(IMConstant.DELETE_C2C_MSG_RAMBLE, IMConstant.ROLE_ADMINISTRATOR), JSON.toJSONString(sendGroupMsg));
        return JSON.parseObject(result, IMResponseMsg.class);
    }
}
